<template>
    <el-form
        :model="account"
        ref="accountForm"
        :rules="rules"
        label-width="80px"
    >
        <el-form-item label="名称" prop="username">
            <el-input v-model="account.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
            <el-input v-model="account.password"></el-input>
        </el-form-item>
        <el-form-item label="昵称">
            <el-input v-model="account.nick"></el-input>
        </el-form-item>
        <el-form-item label="角色">
            <el-select placeholder="选择角色" v-model="account.r_id">
                <el-option
                    v-for="item in roleList"
                    :key="item.r_id"
                    :label="item.rolename"
                    :value="item.r_id"
                >
                </el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="头像">
            <!-- 
                auto-upload :是否自动上传图片
                list-type: 卡片样式
                show-file-list: 上传图片列表
            -->
            <el-upload
                name="headerimg"
                ref="uploadHeader"
                action="/"
                list-type="picture-card"
                :auto-upload="true"
                :show-file-list="false"
                :before-upload="bindBeforeUpload"
                :on-change="bindChangeFile"
            >
                <img v-if="imageUrl" :src="imageUrl" class="avatar-uploader" />
                <el-icon v-else><Plus /></el-icon>
            </el-upload>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="onAccountAddSubmit"
                >确定</el-button
            >
        </el-form-item>
    </el-form>
</template>

<script setup lang="ts">
import { ref, type Ref, onMounted } from 'vue'
import type { IAccountAdd, IRole } from '@/utils/types'
import { RequestRoleList } from '@/api/index'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import {RequestRegister} from '@/api/index'
import  sha256  from 'js-sha256'
const roleList: Ref<Array<IRole>> = ref([])
const account: Ref<IAccountAdd> = ref({
    username: '',
    password: '',
    nick: '',
    r_id: '',
})
const rules = ref({
    username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
    password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
})
let headerimgFile:File
const imageUrl = ref<string>('') //预览图片

defineProps({
    modelValue:Boolean,
})
const emit = defineEmits(['update:modelValue'])
// const emit = defineEmits(['close'])

onMounted(() => {
    getRoleList()
})
/**
 * 角色列表
 */
const getRoleList = async () => {
    const data = await RequestRoleList()
    const { resultCode, resultInfo } = data
    if (resultCode === 1) {
        roleList.value = resultInfo.roles
    }
}

/**
 * 添加账户
 */
const onAccountAddSubmit = () => {
    const {username,password,nick,r_id} = account.value
    const formData = new FormData()
    const psw = sha256(password)
    formData.append('username',username)
    formData.append('password',psw)
    formData.append('nick',nick)
    formData.append('roseid',r_id)
    formData.append('headerimg',headerimgFile)

    RequestRegister(formData).then(data=>{
        const {resultCode,resultInfo} = data
        if(resultCode === 1){
            ElMessage.success('添加账户成功!')
            emit('update:modelValue',false)
            // emit('close')
        }
    })
}

/**
 * 选择本地图片时触发
 * @param rawFile
 */
const bindChangeFile = (rawFile:any) => {
    // 方法一
    // const fileReader = new FileReader()
    // fileReader.addEventListener('load',(obj)=>{
    //     imageUrl.value = obj.currentTarget.result
    // })
    // fileReader.readAsDataURL(rawFile.raw)
    console.log('rawFile ',rawFile);
    headerimgFile = rawFile.raw
    const isOk = onPictureSizeAndType(rawFile.raw)
    // 方法二
    isOk && (imageUrl.value = URL.createObjectURL(rawFile.raw))
}

/**
 * 上传文件之前执行代码
 */
const bindBeforeUpload = (rawFile:File) => {
    console.log('bindBeforeUpload rawFile ', rawFile)
    return false
}

const onPictureSizeAndType = (rawFile:File) => {
    const typeArr = ['image/jpeg','image/png']
    if (!typeArr.includes(rawFile.type) ) {
        ElMessage.error('图片必须是JPG格式或PNG格式!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('图片大小不能超过2MB!')
        return false
    }
    return true
}
</script>

<style scoped>
.avatar-uploader {
    width: 158px;
    height: 158px;
    display: block;
}
</style>
